<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Spring Boot + WebSocket 广播式</title>
</head>
<body onload="disconnect();">
<noscript><h2 style="color: #ff0000;">貌似你的浏览器不支持websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" onclick="disconnect();" disabled="disabled">断开</button>
    </div>
</div>

<div id="conversationDiv">
    <label>输入你的名字</label><input type="text" id="name"/>
    <button id="sendName" onclick="sendName();">发送</button>
    <p id="response"></p>
</div>
<script th:src="@{js/sockjs.js}"></script>
<script th:src="@{js/stomp.js}"></script>
<script th:src="@{js/jquery-2.2.3.js}"></script>
<script>
    var stompClient = null;
    function setConnected(connected) {
        $("#connect").attr("disabled", connected);
        $("#disconnect").attr("disabled", !connected);

        if (connected) {
            $("#conversationDiv").show();
        } else {
            $("#conversationDiv").hide();
        }

        $("#response").html();
    }
    function connect() {
        var socket = new SockJS("/endpointBarton"); // 链接后台可以被用来连接的SockJS端点
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            console.log("Connected:" + frame);
            // 通过stompClient.subscribe订阅/topic/getResponse目标发送的消息,在SendTo里边定义
            // 针对某一个url,等待相应
            stompClient.subscribe("/topic/getResponse", function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            });
        });
    }
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }
    function sendName() {
        var name = $("#name").val();

        // 发送消息及内容
        // 把内容发送给哪一个URL(@MessageMapping)
        stompClient.send("/welcome", {}, JSON.stringify({"name": name}));
    }
    function showResponse(message) {
        var response = $("#response");
        response.html(message);
    }
</script>
</body>
</html>